<template>
  <div>
    <a-steps direction="horizontal" style="margin-top: 40px;width: 76%;flex-wrap: wrap;" :current="1" size="small">
      <a-popover slot="progressDot" slot-scope="{ index, prefixCls }">
        <template slot="content">
          <p style="margin-bottom: 5px;" v-if="getContent(index, 'recordType') === 0">
            提交申请 ：{{ getContent(index, 'approverName') ? getContent(index, 'approverName') : '--' }}
          </p>
          <p style="margin-bottom: 5px;" v-else>
            审批人 ：{{ getContent(index, 'approverName') ? getContent(index, 'approverName') : '--' }}
          </p>
          <p style="margin-bottom: 5px;">单位 ：{{ getContent(index, 'departName') ? getContent(index, 'departName') : '--'
}}</p>
          <p style="margin-bottom: 5px;" v-if="getContent(index, 'recordType') === 0">
            时间：{{ getContent(index, 'createTime') ? getContent(index, 'createTime') : '--' }}
          </p>
          <p style="margin-bottom: 5px;" v-else>
            时间：{{ getContent(index, 'approverTime') ? getContent(index, 'approverTime') : '--' }}
          </p>
          <p style="margin-bottom: 5px;" v-if="getContent(index, 'recordType') !== 0">意见：{{ getContent(index, 'remark')
    ?
    getContent(index, 'remark') : '--'
}}</p>
          <p style="margin-bottom: 5px;" v-if="getContent(index, 'uploadFile') === 1">
            附件：<template v-if="getContent(index, 'nodeFileList') && getContent(index, 'nodeFileList').length > 0">
              <span v-for="item in getContent(index, 'nodeFileList')" :key="item">
                <a @click="geturl(item.fileStorageAddress)">《{{ item.fileName }}》</a>
              </span>
            </template><template v-else>--</template>
          </p>
        </template>
        <span :class="`${prefixCls}-icon-dot`" />
      </a-popover>
      <a-step v-for="(item, index) in list" :key="index" :status="setStatus(item.status)" style="margin-bottom: 28px;">
        <!-- <a-icon v-if="item.recordType === 2" type="exclamation-circle" slot="icon" :style="{ color: '#FE6601', fontSize: '24px' }" /> -->
        <template slot="title" v-if="item.nodeName">
          <span style="font-size: 16px;font-weight: bold;">{{ item.nodeName }}</span>
        </template>
        <div slot="description">
          <p style="font-size: 16px; font-weight: bold;margin: 0 0 5px 0;"
            :class="[item.status == 2 ? 'green' : item.status == 3 ? 'red' : '']">
            {{ item.status == 1 ? '审批人: ' + item.approverName : item.recordType != 0 ? item.statusName : '' }}
          </p>
          <a v-if="isInitiator && item.status === 1" :disabled="item.urgeDisabled ? item.urgeDisabled : false"
            @click.stop="handleUrge(item)">催一下</a>
        </div>
      </a-step>
    </a-steps>
    <div class="isExamine" style="margin-top: 10px;width: 76%;">
      <a-alert v-if="list.length > 0 && !approvalId" message="流程有错误！" description="approvalId找不到" type="error"
        closable />
      <a-row type="flex" v-else>
        <a-form-model ref="formRefs" :rules="validatorRules" :model="form" :label-col="labelCol"
          :wrapper-col="wrapperCol">
          <a-col :span="24">
            <a-form-model-item label="审批结果" prop="status">
              <a-radio-group v-model="form.status" name="radioGroup" :disabled="!isApprover" @change="onchange">
                <a-radio :value="2"> 通过 </a-radio>
                <a-radio :value="3"> 驳回 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="审批意见" prop="remark">
              <a-textarea :auto-size="{ minRows: 3, maxRows: 6 }" v-model="form.remark" placeholder="请输入"
                :disabled="!isApprover" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="Object.keys(form).length > 0 && form.userName">
            <a-form-model-item label="审批人" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-input v-model="form.userName" disabled placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="所属单位" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }"
              v-if="Object.keys(form).length > 0 && form.orgCode">
              <j-select-depart v-model="form.orgCode" :trigger-change="true" customReturnField="orgCode" :multi="true"
                disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="Object.keys(form).length > 0 && form.uploadFile">
            <a-form-model-item label="附件" prop="nodeFileListStr">
              <j-upload v-model="form.nodeFileListStr" :disabled="!isApprover" text="上传文件" bizPath="tempExamine"
                :isMultiple="true" @change="getChange" />
              <a-tooltip placement="topLeft" :title="form.fileDescribe"
                v-if="Object.keys(form).length > 0 && form.fileDescribe">
                <a-icon type="question-circle" />
              </a-tooltip>
              {{ Object.keys(form).length > 0 && form.fileFormat ? '支持扩展名：' + form.fileFormat : '' }}
            </a-form-model-item>
          </a-col>
          <!--//省外异地管控-转出省外：省级+禁毒办-->
          <template v-if="businessType == 5 && isWorkingInfo">
            <a-col :span="12">
              <a-form-model-item label="居住地专干姓名" prop="workingInfo.workingPersonnelName" :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }">
                <a-input v-model="form.workingInfo.workingPersonnelName" :disabled="!isApprover" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="联系方式" prop="workingInfo.workingPersonnelContactInfo" :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }">
                <a-input v-model="form.workingInfo.workingPersonnelContactInfo" :disabled="!isApprover"
                  placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="居住地派出所民警姓名" prop="workingInfo.peoplePoliceName" :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }">
                <a-input v-model="form.workingInfo.peoplePoliceName" :disabled="!isApprover" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="联系方式" prop="workingInfo.peoplePoliceContactInfo" :label-col="{ span: 4 }"
                :wrapper-col="{ span: 20 }">
                <a-input v-model="form.workingInfo.peoplePoliceContactInfo" :disabled="!isApprover" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
          </template>
        </a-form-model>
      </a-row>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { getFileAccessHttpUrl } from '@/api/manage';
import { USER_INFO } from "@/store/mutation-types"
import * as flowServiceApi from '@/api/sjsk/flowService'
var phoneValidator = (rule, value, callback) => {
  if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
    callback()
  } else {
    callback('请输入正确的联系方式')
  }
}

export default {
  props: {
    // 审批流程类型
    businessType: {
      type: [String, Number],
      required: true
    },
    // 流程数组
    list: {
      type: Array
    },
    // 审批流程id
    approvalId: {
      type: [String, Number],
    },
    // 当前审批结果 0：未到审批 1:待审批 2:通过 3:驳回
    status: {
      type: [String, Number],
    },
    // 是否需要审批
    isApprover: {
      type: Boolean
    },
    // 最后节点的审批人是否是当前审批人且是待审批状态
    isWorkingInfo: {
      type: Boolean
    },
    // 审批任务对象
    taskInfo: {
      type: Object
    }
  },
  data() {
    return {
      recordType: { 0: '发起', 1: '审批', 2: '撤销' },
      form: {
        processId: undefined,
        userName: Vue.ls.get(USER_INFO).username,
        orgCode: Vue.ls.get(USER_INFO).orgCode,
        workingInfo: {}
      },
      labelCol: { span: 2 },
      wrapperCol: { span: 22 },
      validatorRules: {
        status: [{ required: true, message: '请选择审批结果', trigger: 'change' },],
        remark: [{ required: false, message: '请输入审批意见', trigger: 'change' },],
        nodeFileListStr: [{ required: false, message: '请上传附件', trigger: 'change' },],
        'workingInfo.workingPersonnelName': [{ required: true, message: '请输入居住地专干姓名', trigger: 'change' },],
        'workingInfo.workingPersonnelContactInfo': [
          { required: true, message: '请输入居住地专干联系方式', trigger: 'change' },
          { validator: phoneValidator },
        ],
        'workingInfo.peoplePoliceName': [{ required: true, message: '请输入居住地派出所民警姓名', trigger: 'change' },],
        'workingInfo.peoplePoliceContactInfo': [
          { required: true, message: '请输入	居住地派出所民警联系方式', trigger: 'change' },
          { validator: phoneValidator },
        ]
      }
    }
  },
  computed: {
    // 发起人的id是否等于当前登录账号的userId
    isInitiator() {
      let bool = false
      let userId = Vue.ls.get(USER_INFO).id //当前用户id
      let col = this.list && this.list.length > 0 && this.list.find(obj => { return obj.approverId === userId && obj.recordType === 0 }) || {}
      if (col && Object.keys(col).length > 0) {
        bool = col.approverId === userId ? true : false
      }
      return bool
    }
  },
  watch: {
    approvalId: {
      immediate: true,
      deep: true,
      handler(val) {
        this.$set(this.form, 'processId', val)
      }
    },
    status: {
      immediate: true,
      deep: true,
      handler(val) {
        let userId = Vue.ls.get(USER_INFO).id //当前用户id
        let filterArr = this.list.filter((col, i) => col.approverId === userId)
        let col = filterArr.length > 0 ? filterArr[filterArr.length - 1] : {}
        this.$set(this.form, 'uploadFile', Object.keys(col).length > 0 && col.uploadFile ? col.uploadFile : '')
        this.$set(this.form, 'fileFormat', Object.keys(col).length > 0 && col.fileFormat ? col.fileFormat : '')
        this.$set(this.form, 'fileDescribe', Object.keys(col).length > 0 && col.fileDescribe ? col.fileDescribe : '')
        this.$set(
          this.form,
          'nodeFileListStr',
          Object.keys(col).length > 0 && col.nodeFileList && Array.isArray(col.nodeFileList)
            ? col.nodeFileList.map((v) => v.fileStorageAddress)
            : ''
        )
        this.validatorRules['nodeFileListStr'].forEach(
          (item) => (item.required = Object.keys(col).length > 0 && col.mustUpload == 1 ? true : false)
        )
        if (val !== 1) {
          // 审批状态为通过或者驳回，才赋值到详情里
          this.$set(this.form, 'remark', Object.keys(col).length > 0 && col.remark ? col.remark : '')
          this.$set(this.form, 'status', Object.keys(col).length > 0 && col.status ? col.status : '')
        }
      }
    }
  },
  methods: {
    // 流程状态样式
    setStatus(value) {
      // 0：未审批，1：待审批，2：通过，3：驳回
      if (value === 1) {
        return 'process'
      } else if (value === 2) {
        return 'finish'
      } else if (value === 3) {
        return 'error'
      }
    },
    // 审批意见是否必填
    onchange(e) {
      console.log(e)
      if (e.target.value == 3) {
        if (this.businessType == 5 && this.isWorkingInfo) {
          this.validatorRules['remark'].forEach(item => item.required = true)
          this.validatorRules['workingInfo.workingPersonnelName'].forEach(item => item.required = false)
          this.validatorRules['workingInfo.workingPersonnelContactInfo'].forEach(item => item.required = false)
          this.validatorRules['workingInfo.peoplePoliceName'].forEach(item => item.required = false)
          this.validatorRules['workingInfo.peoplePoliceContactInfo'].forEach(item => item.required = false)
        }
      } else {
        this.validatorRules['remark'].forEach(item => item.required = false)
        if (this.businessType == 5 && this.isWorkingInfo) {
          this.validatorRules['workingInfo.workingPersonnelName'].forEach(item => item.required = true)
          this.validatorRules['workingInfo.workingPersonnelContactInfo'].forEach(item => item.required = true)
          this.validatorRules['workingInfo.peoplePoliceName'].forEach(item => item.required = true)
          this.validatorRules['workingInfo.peoplePoliceContactInfo'].forEach(item => item.required = true)
        }
      }
      this.$refs['formRefs'].validateField('remark')
      this.$refs['formRefs'].validateField('workingInfo.workingPersonnelName')
      this.$refs['formRefs'].validateField('workingInfo.workingPersonnelContactInfo')
      this.$refs['formRefs'].validateField('workingInfo.peoplePoliceName')
      this.$refs['formRefs'].validateField('workingInfo.peoplePoliceContactInfo')
    },
    // 催一下
    handleUrge() {
      this.$emit('urge')
    },
    // 附件上传完赋值
    getChange(value) {
      console.log(value)
      let data = value ? value.split(',') : []
      let rows = data.map(item => {
        let index = item.indexOf("/")
        let indexsss = item.indexOf("_")
        let resolvesss = item.substring(index + 1, indexsss);
        return {
          fileName: resolvesss,
          fileStorageAddress: item
        }
      })
      this.$set(this.form, 'nodeFileList', rows)
    },
    geturl(url) {
      let urls = getFileAccessHttpUrl(url)
      console.log(urls)
      // location.href=urls
      const elt = document.createElement('a')
      elt.setAttribute('href', urls)
      elt.style.display = 'none'
      document.body.appendChild(elt)
      elt.click();
      document.body.removeChild(elt)
    },
    getContent(index, key) {
      let col = this.list.find((col, i) => i === index)
      if (col && Object.keys(col).length > 0 && key) {
        return col[key]
      }
      if (col && Object.keys(col).length > 0 && !key) {
        return col
      }
    }
  }
}
</script>
<style lang="less" scoped>
.font-gray {
  margin-top: 20px;

  p {
    font-size: 12px;
  }
}

.green {
  color: #52c41a;
}

.red {
  color: #ff4d4f;
}

.blue {
  color: #5a87db;
}
</style>